package org.example3;

import java.io.IOException;
import java.nio.file.*;

public class FolderWatcher {
    /**
     *用于监控目录,目录中增删改文件
     */
    public static void main(String[] args) throws IOException, InterruptedException {
        String path = null;
        if (args.length > 0) {
            path = args[0];
        } else {
            path = "."; // 当前目录
        }

        // 1. 创建 WatchService
        WatchService watchService = FileSystems.getDefault().newWatchService();

        // 2. 注册监控目录（这里以当前目录为例）
        Path dir = Paths.get(path);
        dir.register(watchService,
                StandardWatchEventKinds.ENTRY_CREATE,
                StandardWatchEventKinds.ENTRY_MODIFY,
                StandardWatchEventKinds.ENTRY_DELETE
        );

        System.out.println("开始监控目录: " + dir.toAbsolutePath());

        // 3. 事件处理循环
        while (true) {
            WatchKey key = watchService.take(); // 阻塞等待事件
            for (WatchEvent<?> event : key.pollEvents()) {
                WatchEvent.Kind<?> kind = event.kind();
                Path filename = (Path) event.context();
                System.out.printf("事件类型: %s, 文件名: %s%n", kind, filename);
            }
            key.reset(); // 重置 key，继续监听
        }
    }
}